package com.example.himalayaproject.play.playalbum.playservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import java.io.IOException;

/**
 * 专辑播放服务
 * */
public class AlbumPlayService extends Service {
    private String playUrl32;
    private MediaPlayer player;
    public AlbumPlayService() {
    }

    // 第一步，创建胶水类
    public class AlbumBinder extends Binder {
        public AlbumPlayService getAlbumPlayService () {
            return AlbumPlayService.this;
        }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        playUrl32 = intent.getStringExtra("playUrl32");
        try {
            player.reset();
            player.setDataSource(playUrl32);
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        // 播放资源
//        player = MediaPlayer.create(playUrl32);
    }

    // 播放
    public void start() {
        if (!player.isPlaying()) {
            player.start();
        }
    }

    // 暂停
    public void pause() {
        if (player.isPlaying()) {
            player.pause();
        }
    }

    // 停止
    public void stop () {
        player.stop();
    }

    // 第二步，绑定Service并返回给Activity胶水对象
    @Override
    public IBinder onBind(Intent intent) {
        return new AlbumBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        stop();//解除绑定时，停止播放
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.release();
        player = null;
    }
}
